<template>
  <a-drawer v-model:visible="visible" :title="title" :mask-closable="false" :esc-to-close="false"
    :width="width >= 600 ? 600 : '100%'" @before-ok="save" @close="reset">

    <a-form ref="formRef" :model="form" :rules="rules" size="large" auto-label-width>
      <div v-show="false">
        <a-form-item label="姓名" field="name">
          <a-input v-model.trim="form.name" placeholder="请输入姓名" :max-length="5" show-word-limit />
        </a-form-item>
      </div>
      <a-form-item label="姓氏" field="firstName">
        <a-input v-model.trim="form.firstName" placeholder="请输入姓氏" :max-length="5" show-word-limit />
      </a-form-item>
      <a-form-item label="名字" field="lastName">
        <a-input v-model.trim="form.lastName" placeholder="请输入名字" :max-length="5" show-word-limit />
      </a-form-item>
      <a-form-item label="头像" field="avatar">
        <a-upload :file-list="avatarList" accept="image/*" :show-file-list="false" list-type="picture-card"
          :show-upload-button="true" :on-before-upload="onBeforeUpload">
          <template #upload-button>
            <Avatar :src="avatarList[0].url" :name="form.avatarname" :size="80" trigger>
              <template #trigger-icon><icon-camera /></template>
            </Avatar>
          </template>
        </a-upload>
      </a-form-item>
      <a-form-item label="个人简介" field="introduction">
        <a-textarea v-model.trim="form.introduction" placeholder="请输入个人简介" show-word-limit :max-length="200"
          :auto-size="{ minRows: 3, maxRows: 5 }" />
      </a-form-item>
      <a-form-item label="手机号码" field="phone">
        <a-input v-model.trim="form.phone" placeholder="请输入手机号码" :max-length="11" />
      </a-form-item>
      <a-form-item label="邮箱" field="email">
        <a-input v-model.trim="form.email" placeholder="请输入邮箱" :max-length="255" />
      </a-form-item>
      <a-form-item label="性别" field="gender">
        <a-radio-group v-model="form.gender">
          <a-radio :value="1">男</a-radio>
          <a-radio :value="2">女</a-radio>
          <a-radio :value="0" disabled>未知</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="微信号" field="wechat">
        <a-input v-model.trim="form.wechat" placeholder="请输入微信号" :max-length="20" show-word-limit />
      </a-form-item>
      <a-form-item label="二维码图片" field="picture">
        <a-upload :custom-request="handleUpload" :file-list="fileList" />
        <!-- :accept="audioAcceptTypes"  -->
      </a-form-item>
      <a-form-item label="微信openId" field="openId">
        <a-input v-model.trim="form.openId" placeholder="请输入微信openId" :max-length="99" />
      </a-form-item>
      <a-form-item label="公司" field="companyId">
        <!-- <a-input v-model.trim="form.company" placeholder="请输入公司" :max-length="99" /> -->
        <a-select v-model="form.companyId" placeholder="请选择公司">
          <a-option v-for="item of companyDicList" :key="item.value" :value="item.value" :label="item.label" />
        </a-select>
      </a-form-item>
      <a-form-item label="职位" field="title">
        <a-input v-model.trim="form.title" placeholder="请输入职位" :max-length="99" />
      </a-form-item>
      <!-- <a-form-item label="描述" field="description">
        <a-textarea v-model.trim="form.description" placeholder="请输入描述" show-word-limit :max-length="200"
          :auto-size="{ minRows: 3, maxRows: 5 }" />
      </a-form-item> -->
      <a-form-item label="状态" field="status">
        <a-switch v-model="form.status" :disabled="form.isSystem" :checked-value="1" :unchecked-value="2"
          checked-text="启用" unchecked-text="禁用" type="round" />
      </a-form-item>
    </a-form>
  </a-drawer>

  <a-modal v-model:visible="avatarVisible" title="上传头像" :width="width >= 400 ? 400 : '100%'" :footer="false" draggable
    @close="avatarVisible = false">
    <a-row>
      <a-col :span="14" style="width: 200px; height: 200px">
        <VueCropper ref="cropperRef" :img="avatarOptions.img" :info="true" :auto-crop="avatarOptions.autoCrop"
          :auto-crop-width="avatarOptions.autoCropWidth" :auto-crop-height="avatarOptions.autoCropHeight"
          :fixed-box="avatarOptions.fixedBox" :fixed="avatarOptions.fixed" :full="avatarOptions.full"
          :center-box="avatarOptions.centerBox" :can-move="avatarOptions.canMove" :output-type="avatarOptions.outputType"
          :output-size="avatarOptions.outputSize" @real-time="handleRealTime" />
      </a-col>
      <a-col :span="10" style="display: flex; justify-content: center">
        <div :style="previewStyle">
          <div :style="previews.div">
            <img :src="previews.url" :style="previews.img" alt="" />
          </div>
        </div>
      </a-col>
    </a-row>
    <div style="text-align: center; padding-top: 30px">
      <a-space>
        <a-button type="primary" @click="handleAvatarUpload">确定</a-button>
        <a-button @click="reset">取消</a-button>
      </a-space>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { uploadFile } from '@/apis';
import { addBusinessCard, getBusinessCard, updateBusinessCard, uploadAvatar } from '@/apis/website/businessCard';
import type GiForm from '@/components/GiForm';
import { useForm, type Options } from '@/hooks';
import { useCompanyDict } from '@/hooks/app';
import getAvatar from '@/utils/avatar';
import { Message, type FileItem, type FormInstance, type RequestOption } from '@arco-design/web-vue';
import { useWindowSize } from '@vueuse/core';
import { computed, ref } from 'vue';
import { VueCropper } from 'vue-cropper';
import 'vue-cropper/dist/index.css';

const { companyDicList, getCompanyDicList } = useCompanyDict()

const emit = defineEmits<{
  (e: 'save-success'): void
}>()

const dataId = ref('')
const { width } = useWindowSize()
const isUpdate = computed(() => !!dataId.value)
const title = computed(() => (isUpdate.value ? '修改微信名片' : '新增微信名片'))
const { form, resetForm } = useForm({
  // todo 待补充
  companyId: undefined,
  companyName: ''
})

const selectCompanyName = computed(() => {
  const selectedItem = companyDicList.value.find(item => item.value === form.companyId);
  return selectedItem ? selectedItem.label : '';
})

const formRef = ref<InstanceType<typeof GiForm>>()


// 定义允许的文件类型，可以是 MIME 类型或文件扩展名
const audioAcceptTypes = ['audio/mpeg', 'audio/wav', 'audio/ogg', '.mp3', '.wav', '.ogg'];

//头像上传相关变量
const avatar = {
  uid: '-2',
  name: 'avatar.png',
  url: ''//userInfo.value.avatar,
}
const avatarList = ref<FileItem[]>([avatar])
const fileRef = ref(reactive({ name: 'avatar.png' }))
const avatarOptions: cropperOptions = reactive({
  img: '',
  autoCrop: true,
  autoCropWidth: 160,
  autoCropHeight: 160,
  fixedBox: true,
  fixed: true,
  full: false,
  centerBox: true,
  canMove: true,
  outputSize: 1,
  outputType: 'png',
})


const rules: FormInstance['rules'] = {
  firstName: [{ required: true, message: '请输入姓氏' }],
  lastName: [{ required: true, message: '请输入名字' }],
  phone: [{ required: true, message: '请输入手机号码' }],
  email: [{ required: true, message: '请输入邮箱' }],
  gender: [{ required: true, message: '请选择性别' }],
}


const options: Options = {
  form: { avatarname: 'avatar.png' },
  btns: { hide: true }
}




const previews: any = ref({})
const previewStyle: any = ref({})
// 实时预览
const handleRealTime = (data: any) => {
  previewStyle.value = {
    width: `${data.w}px`,
    height: `${data.h}px`,
    overflow: 'hidden',
    margin: '0',
    zoom: 100 / data.h,
    borderRadius: '50%',
  }
  previews.value = data
}

const avatarBase = ref([] as any)
const cropperRef = ref()
// 上传头像
const handleAvatarUpload = async () => {
  cropperRef.value.getCropBlob((data: any) => {
    const formData = new FormData()
    formData.append('avatarFile', data, fileRef.value?.name)
    uploadAvatar(formData).then((res) => {
      //form.avatar = res.data.avatar
      avatarBase.value = res.data.avatar
      //console.log("avatar:" + res.data.avatar)
      avatarList.value[0].url = getAvatar(res.data.avatar, undefined)
      avatarVisible.value = false
      Message.success('更新成功')
    })
  })
}

const fileList = ref([] as any)
//上传图片
const handleUpload = (options: RequestOption) => {
  const controller = new AbortController()
    ; (async function requestWrap() {
      const { onProgress, onError, onSuccess, fileItem, name = 'file' } = options
      onProgress(20)
      const formData = new FormData()
      formData.append(name as string, fileItem.file as Blob)
      try {
        const res = await uploadFile(formData)
        Message.success('上传成功')
        fileList.value.push({
          uid: '-1',
          name: 'upload1.jpg',
          url: res.data.url
        })
        onSuccess(res)
      } catch (error) {
        onError(error)
      }
    })()
  return {
    abort() {
      controller.abort()
    },
  }
}


const avatarVisible = ref(false)
// 打开裁剪框
const onBeforeUpload = (file: File): boolean => {
  fileRef.value = file
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = () => {
    avatarOptions.img = reader.result
  }
  avatarVisible.value = true
  return false
}

// 重置
const reset = () => {
  formRef.value?.resetFields()

  fileRef.value = { name: '' }
  avatarOptions.img = ''
  avatarVisible.value = false
  fileList.value = []
  resetForm()
}



const visible = ref(false)
// 新增
const onAdd = () => {
  if (!companyDicList.value.length) {
    getCompanyDicList()
  }

  reset()
  dataId.value = ''
  visible.value = true
}


// 修改
const onUpdate = async (id: string) => {
  if (!companyDicList.value.length) {
    getCompanyDicList()
  }

  reset()
  dataId.value = id
  const res = await getBusinessCard(id)
  Object.assign(form, res.data)
  visible.value = true

  //console.log(res.data);
  if (res.data.picture.length) {
    fileList.value.push({
      uid: res.data.id,
      name: 'wechatPicture.jpg',
      url: res.data.picture
    })
  }

  if (res.data.avatar.length) {
    avatarList.value[0].url = res.data.avatar
  }
  console.log(avatarList.value)
}

// 保存
const save = async () => {
  try {
    const isInvalid = await formRef.value?.validate()
    if (isInvalid) return false

    //上传的二维码图片
    if (fileList.value.length) {
      form.picture = fileList.value[0].url
    }

    //上传的用户头像
    if (avatarBase.value.length) {
      form.avatar = avatarBase.value
    }

    form.name = form.firstName + form.lastName;

    form.companyName = selectCompanyName

    // console.log(form.companyId)
    // console.log(form.companyName)
    // return false
    if (isUpdate.value) {

      await updateBusinessCard(form, dataId.value)
      Message.success('修改成功')
    } else {
      await addBusinessCard(form)
      Message.success('新增成功')
    }
    emit('save-success')
    return true
  } catch (error) {
    return false
  }
}




defineExpose({ onAdd, onUpdate })
</script>

<style scoped lang="scss">
:deep(.arco-avatar-trigger-icon-button) {
  width: 32px;
  height: 32px;
  line-height: 32px;
  background-color: #e8f3ff;

  .arco-icon-camera {
    margin-top: 8px;
    color: rgb(var(--arcoblue-6));
    font-size: 14px;
  }
}

.body {
  display: flex;
  flex-direction: column;
  padding: 28px 10px 20px 10px;

  .btn {
    cursor: pointer;
  }

  &>section {
    flex: 1 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 32px 0 50px;

    .name {
      font-size: 20px;
      margin: 20px 0;
    }

    .id {
      span {
        font-size: 12px;
        font-weight: 400;
        line-height: 20px;
        padding: 0 6px;
        color: var(--color-text-3);
      }
    }
  }

  &>footer .footer_item {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
    font-size: 12px;
  }
}

.footer {
  margin: 0 -16px;
  padding-top: 16px;
  font-size: 12px;
  text-align: center;
  border-top: 1px solid var(--color-border-2);
}
</style>
